<?php
global $framework;
require_once($framework."/helpers/debug.helpers.php");
require_once($framework."/helpers/template.helpers.php");
require_once($framework."/helpers/i18n.helpers.php");
require_once($framework."/helpers/image.helpers.php");
require_once($framework."/helpers/string.helpers.php");
require_once($framework."/router.php");
require_once($framework."/persistence/data.php");
require_once($framework."/exception/entitynotfoundexception.php");
require_once($framework."/session.php");
require_once($framework."/html/html.php");
require_once($framework."/html/forms.php");
require_once($framework."/html/fields.php");
/**
 * Core web application class, managing entities and navigation.
 * @author delormef
 * @version $revision$
 */
abstract class WebApp {
	
	/**
	 * Instance of the Class.
	 * @var WebApp instance.
	 */
	protected static $_instance;
	
	/**
	 * Flag imaging the initialiing process of the application.
	 * @var boolean flag about initialization.
	 */
	protected static $_initialized=false;
	
	/**
	 * Application name
	 * @var string containing the name of the web app.
	 */
	protected static $_appname;
	
	/**
	 * List of action for wich no master template must be used.
	 * @var array of string
	 */
	public static $_noMasterTemplateFor=array();
	
	
	/**
	 * template to be render on the current action.
	 * @var unknown_type
	 */	
	public static $_templateAction;

	/**
	 * Array containting all the entities to be displayed on the page.
	 * @var array.
	 */
	public static $_entities = array();
	
	/**
	 * Action for the current user.
	 * @var string, default value is the 'list' action.
	 */
	public $action="";
	
	/**
	 * Array containing the currently selected entity to be display in
	 * mode action="show"
	 * @var array.
	 */
	public $showEntity = array();

	
	protected $_name = "";
	
	/**
	 * Parameterized constructor for the manager. 
	 * @param $appname Name of the application.
	 */
	public function __construct($appname){
		__debug(__CLASS__."::__construct() - start: appname=$appname",__FILE__,__LINE__);
		if(self::$_initialized==false){
			$this->appname=$appname;
			// test if entity are generated. If not, generate them.
			$this->generateEntityFolder();
			if(file_exists($_SERVER['DOCUMENT_ROOT']."/webapp/entities/"))
			Session::start();
			self::$_initialized=true;
		}
		__debug(__CLASS__."::__construct() - end",__FILE__,__LINE__);
	}
	

		/**
	 * Initialize WebApp with some common data.
	 * @return unknown_type
	 */	
	abstract public function initialize();
	/*{
		__debug(__CLASS__."::Initialize() - Initialize WebApp.",__FILE__,__LINE__);
		//self::setDefaultManager();
		//Router::getManager($this->manager)->initialize();
	}*/
	
	
	/**
	 * Starting point of execution for the webapp
	 */
	public function run(){
		__debug(__CLASS__."::run()",__FILE__,__LINE__);
		self::$_templateAction = Router::actions($_SERVER['REQUEST_URI'] );
		$this->render();	
	}
	/**
	 * set the value of the default manager.
	private function getDefaultManager(){
		$defManager = Router::getManager()->getDefaultManager(); 
		return $defManager;
	}
	 */
		
	/**
	 * Run rendering of the page.
	 */
	public function render(){
		__debug(__CLASS__."::render() - start",__FILE__,__LINE__);
		if(isset($_REQUEST['ajax'])){
			__debug(__CLASS__."::render() - Rend action [".$this->action."] template [".self::$_templateAction."].",__FILE__,__LINE__);
			$this->renderAction();
			self::$_noMasterTemplateFor=true;
		}else{
			__debug(__CLASS__."::render() - Rend application template.",__FILE__,__LINE__);
			__template("application/application");
		}
		__debug(__CLASS__."::render() - end",__FILE__,__LINE__);
	}
	/**
	 * 
	 * @param $template
	 * @return unknown_type
	 */
	public function renderAction(){
		__debug(__CLASS__."::renderAction() - Rendering the template: ".self::$_templateAction.".",__FILE__,__LINE__);
		__template("managers/".self::$_templateAction);
	}
	/**
	 * Add $entityName as a new list of entities($entityList) to be managed by application.
	 * @param $entityName
	 * @param $entityList
	 * @return unknown_type
	 */
	protected function addEntity($entityName="", $entityList=""){
		__debug(__CLASS__."::addEntity() - start : entityName=$entityName, count(entitylist)=".count($entityList).").",__FILE__,__LINE__);
		if(empty(self::$_entities[$entityName])){
			self::$_entities[$entityName]= array();
		}
		self::$_entities[$entityName] = $entityList;
		__debug(__CLASS__."::addEntity() - end.",__FILE__,__LINE__);
	}

	/**
	 * set $entityName with the list of entities($entityList) to be managed by application.
	 * @param $entityName
	 * @param $entityList
	 * @return unknown_type
	 */
	protected function setEntity($entityName="", $entityList=""){
		self::$_entities[$entityName] = $entityList;
	}
	
	/**
	 * Return all entities already loaded into page buffer.
	 * @param $type
	 * @return unknown_type
	 */
	public function getEntities($type){
		__debug(__CLASS__."::getEntities() - start: type=$type",__FILE__,__LINE__);

		if(!empty(self::$_entities[$type])){
			return self::$_entities[$type];
		}else{
			__error(__CLASS__."::getEntities() Can't find entity named \"$type\" into entities attribute.",__FILE__,__LINE__);
			return array();
		}
		__debug(__CLASS__."::getEntities() - end",__FILE__,__LINE__);
	}

	/**
	 * Return the loaded entity to be displayed in show mod.
	 * @return unknown_type
	public function getShowEntity(){
		return $this->showEntity;
	}
	 */
	
	/**
	 * Return the selected action.
	 * @return unknown_type
	 */
	public function getAction(){
		__debug(__CLASS__."::getAction() =>action=".$this->action,__FILE__,__LINE__);
		return $this->action;
	}

	/**
	 * test if any entity exist into the <em>/entities</em> directory.
	 * If not, try to generate them from the <em>schema.ini</em> file.
	 * @return boolean: flag if true=> ok, entities exists. false => stop 
	 * application with the standard error page. 
	 */
	private function generateEntityFolder(){
		global $framework;
		__debug(__CLASS__."::generateEntityFolder() - start",__FILE__,__LINE__);
		$state=false;
		$entityclasspath=dirname(__FILE__)."/../webapp/entities/";
	    if ($dh = opendir($entityclasspath)) {
	        while((($item = readdir($dh)) !== false)&& $state==false){
                if(!empty($item)
                	&& $item!="." 
	        		&& $item!=".."
	        		&& $item!="Thumbs.db" 
	        		&& strpos($item,".entity.php")!==false ){
						__debug(__CLASS__."::generateEntityFolder() - entity file:$item",__FILE__,__LINE__);
	        			$state=true;
	        	}
	        }
	        closedir($dh);
	    }
	    // need to generate files *.entity.php
	    if(!$state){
	    	require_once($framework."/model.php");
	    	$model=new Model();
	    	$model->generate();
	    }
		__debug(__CLASS__."::generateEntityFolder() - return=$state",__FILE__,__LINE__);
	    return $state;
	}
	
	/**
	 * Return name of the current Manager.
	 * @return striong containing the name of the manager.
	 */
	public function getName(){
		return $this->_name;
	}
	
}
?>